<!DOCTYPE html>
<html>
	<head>
		<title>KacTech- Your Fresh Videos</title>
		<style type="text/css">
			.ytPlayer {
				position: fixed;
				left: 500px;
				top: 100px;
				-webkit-border-radius: 15px;
				-moz-border-radius: 15px;
				border-radius: 15px;
				background: black;
			}
			#ytPlayer {
				padding: 10px;
			}
			#search-container {
				width: 430px;
				height: 325px;
			}
			.videoItem {
				padding: 10px;
				-webkit-border-radius: 15px;
				-moz-border-radius: 15px;
				border-radius: 15px;
				border-style: dotted;
				margin: 5px;
				padding: 10px;
			}
			.videoSelected {
				background-color: papayawhip;
			}
			#queries {
				padding: 10px;
			}
			.queryLabel {
				padding: 5px;
				margin: 5px;
				-webkit-border-radius: 10px;
				-moz-border-radius: 10px;
				border-radius: 10px;
				background-color: orange;
			}
			.videoDate {
				font-weight: bold;
			}
		</style>
	</head>
	<body>
		<h2>KacTech- Your Fresh Videos</h2>
		<div>
			<div id="buttons">
				<label>
					<input id="query" value='' type="text"/>
					<button id="search-button" disabled onclick="search()" >
						Add Query
					</button></label>
			</div>
			<div id="queries"></div>
			<div id="search-container"></div>
		</div>
		<div class="ytPlayer">
			<iframe id="ytPlayer" width="420" height="315" src="http://www.youtube.com/embed/" frameborder="0" allowfullscreen></iframe>
		</div>
		<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
		<!--
		<script src="jquery.cookie.js"></script>
		<script src="auth.js"></script>
		<script src="search.js"></script>
		-->
		<script type="text/javascript">
			/*
			 * jQuery Cookie Plugin v1.3
			 * https://github.com/carhartl/jquery-cookie
			 *
			 * Copyright 2011, Klaus Hartl
			 * Dual licensed under the MIT or GPL Version 2 licenses.
			 * http://www.opensource.org/licenses/mit-license.php
			 * http://www.opensource.org/licenses/GPL-2.0
			 */
			(function($, document, undefined) {

				var pluses = /\+/g;

				function raw(s) {
					return s;
				}

				function decoded(s) {
					return decodeURIComponent(s.replace(pluses, ' '));
				}

				var config = $.cookie = function(key, value, options) {

					// write
					if (value !== undefined) {
						options = $.extend({}, config.defaults, options);

						if (value === null) {
							options.expires = -1;
						}

						if ( typeof options.expires === 'number') {
							var days = options.expires, t = options.expires = new Date();
							t.setDate(t.getDate() + days);
						}

						value = config.json ? JSON.stringify(value) : String(value);

						return (document.cookie = [encodeURIComponent(key), '=', config.raw ? value : encodeURIComponent(value), options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
						options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : ''].join(''));
					}

					// read
					var decode = config.raw ? raw : decoded;
					var cookies = document.cookie.split('; ');
					for (var i = 0, l = cookies.length; i < l; i++) {
						var parts = cookies[i].split('=');
						if (decode(parts.shift()) === key) {
							var cookie = decode(parts.join('='));
							return config.json ? JSON.parse(cookie) : cookie;
						}
					}

					return null;
				};

				config.defaults = {};

				$.removeCookie = function(key, options) {
					if ($.cookie(key) !== null) {
						$.cookie(key, null, options);
						return true;
					}
					return false;
				};

			})(jQuery, document);
		</script>

		<script type="text/javascript">
			var API_KEY = 'AIzaSyBbZs1w_MOllxeQD-EV1_ORjr6RZFgtKxg';
			googleApiClientReady = function() {
				gapi.client.setApiKey(API_KEY);
				gapi.client.load('youtube', 'v3', function() {
					handleAPILoaded();
				});
			}
		</script>

		<script type="text/javascript">
			function handleAPILoaded() {
				$('#search-button').attr('disabled', false);
				$('#query').keypress(function(e) {
					code = (e.keyCode ? e.keyCode : e.which);
					if (code == 13)
						search();
				});
				var qs = getQueriesFromCookie();
				for (var q in qs) {
					addQueryToBox(qs[q]);
				}
				recursiveQuery(qs, 0);
			}

			function recursiveQuery(qs, n) {
				console.log("rec " + n);
				if (n < qs.length) {
					makeRequest(qs[n]).execute(function(response) {
						addToList(response.result.items);
						recursiveQuery(qs, n + 1);
					});
				} else
					display(videoList);
			}

			function addQueryToBox(q) {
				var span = $('<span/>', {
					text : q,
					class : 'queryLabel'
				});
				var a = $('<a/>', {
					href : '#',
					text : 'X',
				});
				a.click({
					t : q
				}, function(event) {
					removeQueryFromCookie(event.data.t);
					$(event.target.parentNode).remove()
					//console.log(event.data.t);
					return false;
				});
				span.append(a).appendTo('#queries');
			}

			var videoList = [];

			// Search for a given string.
			function search() {
				var q = $('#query').val();
				$('#query').val('');
				addQueryToBox(q);
				addQueryToCookies(q);
				makeRequest(q).execute(function(response) {
					addToList(response.result.items);
					display(videoList);
				});
			}

			function addToList(items) {
				for (var item in items) {
					item = items[item];
					videoList[item.snippet.publishedAt + item.etag] = item;
				}
				var keys = [];
				for (var li in videoList)
				keys.push(li);
				keys.sort();
				keys.reverse();
				var nl = [];
				for (var key in keys) {
					key = keys[key];
					nl[key] = videoList[key];
				}
				videoList = nl;
			}

			function makeRequest(q) {
				return gapi.client.youtube.search.list({
					q : q,
					part : 'snippet',
					maxResults : 20,
					order : 'date',
					type : 'video',
				});
			}

			function addQueryToCookies(q) {
				var qs = getQueriesFromCookie();
				qs.push(q);
				$.cookie("queries", JSON.stringify(qs), {
					expires : 7
				});
			}

			function getQueriesFromCookie() {
				var s = $.cookie("queries");
				return s ? JSON.parse(s) : [];
			}

			function removeQueryFromCookie(q) {
				var qs = getQueriesFromCookie();
				var idx = qs.indexOf(q);
				if (idx >= 0) {
					qs.splice(idx, idx == 0 ? 1 : idx);
					$.cookie("queries", JSON.stringify(qs), {
						expires : 7
					});
				}
			}

			function display(items) {
				var container = $('#search-container');
				container.empty();
				var n = 1;
				for (var item in items) {
					//console.log(items[item].snippet.title);
					var div = $('<div/>', {
						class : 'videoItem',
					});
					var a = $('<a/>', {
						id : 'v_' + items[item].id.videoId,
						title : items[item].snippet.title,
						href : 'http://www.youtube.com/watch?v=' + items[item].id.videoId,
					});
					a.click({
						v : items[item].id.videoId
					}, function(event) {
						$('#ytPlayer').attr('src', 'http://www.youtube.com/embed/' + event.data.v + '?autoplay=1');
						$('.videoSelected').removeClass('videoSelected');
						$(event.target.parentNode.parentNode).addClass('videoSelected');
						return false;
					});
					var img = $('<img/>',{src: items[item].snippet.thumbnails['default'].url,});
					var date = new Date(items[item].snippet.publishedAt);
					div.append($('<div/>', {
						text : '#' + (n++) + ' ' + (date.getYear() - 100) + '/' + (date.getMonth() + 1) + '/' + date.getDate() + ' ' + date.getHours() + ':' + minutes(date.getMinutes()),
						class : 'videoDate',
					}));
					a.append($('<div/>', {
						text : items[item].snippet.title
					}));
					a.append(img);
					div.append(a);
					container.append(div);
				}
			}

			function minutes(min) {
				return min < 10 ? '0' + min : '' + min;
			}
		</script>
		<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
	</body>
</html>
